import React, { useState, useEffect } from 'react';
import { get, post } from '@/lib/request';
import dayjs from 'dayjs';
import {
    Avatar,
    AvatarImage,
    AvatarFallback
} from "@/components/ui/avatar";
import { Button } from "@/components/ui/button"
import {
    Drawer,
    DrawerClose,
    DrawerContent,
    DrawerDescription,
    DrawerFooter,
    DrawerHeader,
    DrawerTitle,
    DrawerTrigger,
} from "@/components/ui/drawer";
import {
    Pagination,
    PaginationContent,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
} from "@/components/ui/pagination";
import { Separator } from "@/components/ui/separator"
const tradeTypeClassMapping = {
    '支出': 'bg-red-600',
    '收入': 'bg-green-600',
    '转账': 'bg-blue-600',
    '预算': 'bg-violet-600'
};
export default function ({ bookId, accountNo, month, day, tags = [], primaryTags = [] }) {
    const MAX_SHOW_PAGE = 4;
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPage, setTotalPage] = useState(0);
    const [total, setTotal] = useState(0);
    const [funds, setFunds] = useState([]);
    const [showFundDetail, setShowFundDetail] = useState(false);
    const [currentSelectFund, setCurrentSelectFund] = useState();
    const loadFunds = async () => {
        return get('/api/funds', { bookId, accountNo, day, tags: (tags || []).join(','), page: currentPage, pageSize: 20 })
            .then(({ current, total, totalPage, data }) => {
                setTotalPage(totalPage);
                setTotal(total);
                setFunds(data.map(item => {
                    return {
                        ...item,
                        tags: item.tags ? item.tags.split(',') : []
                    }
                }));
            });
    }
    useEffect(() => {
        loadFunds();
    }, [bookId, accountNo, month, day, tags, currentPage]);
    return <div className="w-full mx-auto">
        <div className="p-4 bg-white rounded-lg border shadow-md sm:p-8 dark:bg-gray-800 dark:border-gray-700 w-full">
            <div className="flex justify-between items-center mb-4">
                <h3 className="text-sm text-muted-foreground">
                    Total of {total} fund details
                </h3>
                <div
                    className="text-sm font-medium"
                >
                    {
                        totalPage > 1 ? <Pagination>
                            <PaginationContent>
                                {Array.from({ length: Math.min(totalPage, MAX_SHOW_PAGE) }, (_, index) => index + 1).map(showIndex => {
                                    if (totalPage < MAX_SHOW_PAGE) {
                                        return <PaginationItem>
                                            <PaginationLink href="#" onClick={() => setCurrentPage(showIndex)} isActive={currentPage === showIndex}>{showIndex}</PaginationLink>
                                        </PaginationItem>
                                    } else {
                                        if (showIndex === 1) {
                                            // 第一页
                                            return <PaginationItem>
                                                <PaginationLink href="#" onClick={() => setCurrentPage(1)} isActive={currentPage === 1}>{1}</PaginationLink>
                                            </PaginationItem>
                                        } else if (showIndex === MAX_SHOW_PAGE) {
                                            // 最后部分
                                            if (currentPage < totalPage) {
                                                return <PaginationItem>
                                                    <PaginationEllipsis onClick={() => setCurrentPage(Math.max(currentPage + 1, showIndex))} />
                                                </PaginationItem>
                                            } else {
                                                return <PaginationItem>
                                                    <PaginationLink href="#" onClick={() => setCurrentPage(totalPage)} isActive={currentPage === totalPage}>{totalPage}</PaginationLink>
                                                </PaginationItem>
                                            }
                                        } else {
                                            // 中间部分
                                            let cacluatePage;
                                            if (currentPage < totalPage) {
                                                if (currentPage < MAX_SHOW_PAGE) {
                                                    cacluatePage = showIndex;
                                                } else {
                                                    cacluatePage = currentPage - (MAX_SHOW_PAGE - showIndex - 1);
                                                }
                                            } else {
                                                cacluatePage = totalPage - (MAX_SHOW_PAGE - showIndex);
                                            }

                                            return <PaginationItem>
                                                <PaginationLink href="#" onClick={() => setCurrentPage(cacluatePage)} isActive={currentPage === cacluatePage}>{cacluatePage}</PaginationLink>
                                            </PaginationItem>
                                        }
                                    }

                                })}
                            </PaginationContent>
                        </Pagination> : ''
                    }
                </div>
            </div>
            <div className="flow-root">
                <ul role="list" className="divide-y divide-gray-200 dark:divide-gray-700">
                    {funds.length > 0 ? funds.map(fund => {
                        return <li class="py-3 sm:py-4" onClick={() => {
                            setCurrentSelectFund(fund);
                            setShowFundDetail(true);
                        }}>
                            <div className="flex items-center space-x-4">
                                <div class="w-9 flex-none">
                                    <Avatar className="w-8 h-8 rounded-full">
                                        <AvatarImage src={`https://sg-funds-center.oss-cn-hangzhou.aliyuncs.com/funds/gpt/${fund.create_account_no}.jpg`} alt="Avatar" />
                                        <AvatarFallback>Fail</AvatarFallback>
                                    </Avatar>
                                </div>
                                <div className="flex-1">
                                    <div>
                                        <div className="text-sm font-medium text-gray-900 dark:text-white flex gap-1 w-full">
                                            <span>{fund.create_account_name}</span>
                                            {fund.tags.slice(0, 3).sort((a, b) => a.length - b.length).sort((a, b) => primaryTags.indexOf(b) - primaryTags.indexOf(a)).map(tag => {
                                                return <span className={`center relative inline-block select-none whitespace-nowrap rounded-lg border-transparent text-primary-foreground py-1.5 px-2 align-baseline font-sans font-bold uppercase leading-none text-white ${primaryTags.includes(tag) ? 'bg-primary' : 'bg-gray-600'}`}
                                                    style={{ fontSize: '0.6rem' }}
                                                    key={`${fund.id}-${tag}`}>
                                                    {tag}
                                                </span>
                                            })}
                                            {
                                                fund.tags.length > 3 ? "..." : ""
                                            }
                                        </div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400 w-full mt-2">
                                            {fund.remark}
                                        </div>
                                    </div>
                                </div>
                                <div class="w-9 flex-none right-0 inline-flex items-center text-base font-semibold text-gray-900 dark:text-white">
                                    <div>
                                        <div>{fund.trade_amount}</div>
                                        <div className={`center relative inline-block select-none whitespace-nowrap rounded-lg border-transparent text-primary-foreground py-1.5 px-2 align-baseline font-sans font-bold uppercase leading-none text-white ${tradeTypeClassMapping[fund.trade_type] || 'bg-primary'}`} style={{ fontSize: '0.6rem' }}>
                                            {fund.trade_type}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </li>
                    }) : <div className="ant-empty ant-empty-normal mt-2">
                        <div className="ant-empty-image">
                            <svg
                                className="ant-empty-img-simple"
                                width={64}
                                height={41}
                                viewBox="0 0 64 41"
                                xmlns="http://www.w3.org/2000/svg"
                            >
                                <g transform="translate(0 1)" fill="none" fillRule="evenodd">
                                    <ellipse
                                        className="ant-empty-img-simple-ellipse"
                                        cx={32}
                                        cy={33}
                                        rx={32}
                                        ry={7}
                                    />
                                    <g className="ant-empty-img-simple-g" fillRule="nonzero">
                                        <path d="M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z" />
                                        <path
                                            d="M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z"
                                            className="ant-empty-img-simple-path"
                                        />
                                    </g>
                                </g>
                            </svg>
                        </div>
                        <div className="ant-empty-description">暂无明细数据</div>
                    </div>}
                </ul>
            </div>
            <Drawer open={showFundDetail} onOpenChange={value => setShowFundDetail(value)}>
                <DrawerContent>
                    <div className="mx-auto w-full max-w-sm">
                        <DrawerHeader>
                            <DrawerTitle>Fund Detail</DrawerTitle>
                            <DrawerDescription>View the specified fund details.</DrawerDescription>
                        </DrawerHeader>
                        <div className="p-4 pb-0 h-96 overflow-y-auto">
                            <div className="mt-3">
                                <div className="grid gap-3">
                                    <div className="font-semibold">Basic Information</div>
                                    <ul className="grid gap-3">
                                        <li className="flex items-center justify-between">
                                            <span className="text-muted-foreground">Fund ID</span>
                                            <span>{currentSelectFund?.id || '-'}</span>
                                        </li>
                                        <li className="flex items-center justify-between">
                                            <span className="text-muted-foreground">
                                                Trade Type
                                            </span>
                                            <div className={`center relative inline-block select-none whitespace-nowrap rounded-lg border-transparent text-primary-foreground py-1.5 px-2 align-baseline font-sans font-bold uppercase leading-none text-white ${tradeTypeClassMapping[currentSelectFund?.trade_type] || 'bg-primary'}`}
                                                style={{ fontSize: '0.75rem' }}>
                                                {currentSelectFund?.trade_type || '-'}
                                            </div>
                                        </li>
                                        <li className="flex items-center justify-between">
                                            <span className="text-muted-foreground">
                                                Trade Amount
                                            </span>
                                            <span>RMB {currentSelectFund?.trade_amount || '-'}</span>
                                        </li>
                                    </ul>
                                    <Separator className="my-2" />
                                    <ul className="grid gap-3">

                                        <li className="flex items-center justify-between">
                                            <span className="text-muted-foreground">Book Name</span>
                                            <span>{currentSelectFund?.book_name || '-'}</span>
                                        </li>
                                        <li className="flex items-center justify-between">
                                            <span className="text-muted-foreground">Create Time</span>
                                            <span>{currentSelectFund ? dayjs(currentSelectFund.create_time).format('YYYY-MM-DD HH:mm:ss') : '-'}</span>
                                        </li>
                                        <li className="flex items-center justify-between">
                                            <span className="text-muted-foreground">Create Terminal</span>
                                            <span>{currentSelectFund?.terminal || '-'}</span>
                                        </li>
                                    </ul>
                                </div>
                                <Separator className="my-4" />
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="grid gap-3">
                                        <div className="font-semibold">Tags Information</div>
                                        <address className="grid gap-0.5 not-italic text-muted-foreground">
                                            {(currentSelectFund?.tags || []).sort((a, b) => a.length - b.length).sort((a, b) => primaryTags.indexOf(b) - primaryTags.indexOf(a)).map(tag => {
                                                return <span className={`center relative inline-block select-none whitespace-nowrap rounded-lg border-transparent text-primary-foreground py-1.5 px-2 align-baseline font-sans font-bold uppercase leading-none text-white ${primaryTags.includes(tag) ? 'bg-primary' : 'bg-gray-600'}`}
                                                    style={{ fontSize: '0.75rem' }}
                                                    key={`${currentSelectFund.id}-${tag}`}>
                                                    {tag}
                                                </span>
                                            })}
                                        </address>
                                    </div>
                                    <div className="grid auto-rows-max gap-3">
                                        <div className="font-semibold">Remark</div>
                                        <div>
                                            {currentSelectFund?.remark || '-'}
                                        </div>
                                    </div>
                                </div>
                                <Separator className="my-4" />
                                <div className="grid gap-3">
                                    <div className="font-semibold">Account Information</div>
                                    <dl className="grid gap-3">
                                        <div className="flex items-center justify-between">
                                            <dt className="text-muted-foreground">Create Acount No</dt>
                                            <dd>{currentSelectFund?.create_account_no || '-'}</dd>
                                        </div>
                                        <div className="flex items-center justify-between">
                                            <dt className="text-muted-foreground">Create Acount Name</dt>
                                            <dd>{currentSelectFund?.create_account_name || '-'}</dd>
                                        </div>
                                        <div className="flex items-center justify-between">
                                            <dt className="text-muted-foreground">From Acount No</dt>
                                            <dd>
                                                <a href="mailto:">{currentSelectFund?.from_account_no || '-'}</a>
                                            </dd>
                                        </div>
                                        <div className="flex items-center justify-between">
                                            <dt className="text-muted-foreground">From Account Name</dt>
                                            <dd>
                                                <a href="mailto:">{currentSelectFund?.from_account_name || '-'}</a>
                                            </dd>
                                        </div>
                                        <div className="flex items-center justify-between">
                                            <dt className="text-muted-foreground">To Acount No</dt>
                                            <dd>
                                                <a href="tel:">{currentSelectFund?.to_account_no || '-'}</a>
                                            </dd>
                                        </div>
                                        <div className="flex items-center justify-between">
                                            <dt className="text-muted-foreground">To Account Name</dt>
                                            <dd>
                                                <a href="tel:">{currentSelectFund?.to_account_name || '-'}</a>
                                            </dd>
                                        </div>
                                    </dl>
                                </div>
                                <Separator className="my-4" />
                                <div className="grid gap-3 mb-2">
                                    <div className="font-semibold">Actions Support</div>
                                    <dl className="grid gap-3">
                                        <Button variant="outline" disabled>Update Fund</Button>
                                        <Button variant="destructive" disabled>Delete Fund</Button>
                                    </dl>
                                </div>
                            </div>
                        </div>
                    </div>
                </DrawerContent>
            </Drawer>
        </div>
    </div>
}
